import { getMdStockList } from "@/api/stock/store";
import { dealDataExcept } from "@/utils/common";
import { message } from "@/utils/message";
import { handleTree } from "@/utils/tree";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import { ElMessageBox } from "element-plus";
import { h, onMounted, reactive, type Ref, ref } from "vue";

// 组件
import { addDialog } from "@/components/ReDialog";
import { DictTag } from "@/components/common/DictTag";
import { ImageViewer } from "@/components/common/ImageViewer";
import { GodownStock } from "../components";

// api
import {
  getDepositoryPage,
  getProductPage,
  getSupplierSimplePage
} from "@/api/common"; // 公共接口

const treeLoading = ref(false);
const treeData = ref([]);

export function useStoreOrder(tableRef?: Ref, treeRef?: Ref) {
  const isStoreManager = ref(0); // 是否驻店店长角色
  const selectData = ref({
    ckList: [],
    gysList: []
  });
  const totalForm = ref<any>({});
  const form = reactive({
    categoryId: "",
    goodsCode: "",
    goodsName: "",
    goodsType: "",
    supplierId: "",
    depositoryId: "",
    minActualNum: null,
    maxActualNum: null,
    minCanUseNum: null,
    maxCanUseNum: null,
    businessDate: [],
    businessDateBegin: "",
    businessDateEnd: "",
    pageNum: 1,
    pageSize: 20
  });
  const currentTreeData = reactive({
    id: null,
    menuName: ""
  });
  const dataList = ref([]);
  const loading = ref(false);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 50, 100, 200],
    background: true
  });

  const columns: TableColumnList = [
    {
      type: "expand",
      slot: "expand",
      fixed: "left",
      width: "30px"
    },
    {
      label: "商品名称/规格名称",
      prop: "businessDate",
      width: 280,
      align: "left",
      fixed: "left",
      showOverflowTooltip: true,
      cellRenderer: ({ row }) => (
        <div class="flex items-center text-cut">
          <ImageViewer radius="8px" src={row.imageJson} />
          <div class="ml-2 flex-1 text-cut">{row.goodsName}</div>
        </div>
      )
    },
    {
      label: "商品编码/规格编码",
      prop: "storeOrderCode",
      align: "left",
      width: 180,
      showOverflowTooltip: true,
      formatter: row => row.specCode || row.goodsCode
    },
    {
      label: "所属门店",
      prop: "storeName",
      align: "left",
      width: 130
    },
    {
      label: "商品条码",
      prop: "barCode",
      width: 150,
      slot: "barCode"
    },
    {
      label: "实际库存",
      prop: "actualNum",
      minWidth: 95
    },
    {
      label: "在途库存",
      prop: "sendNum",
      width: 120
    },
    {
      label: "可用库存",
      prop: "canUseNum",
      width: 120
    },
    {
      label: "锁定库存",
      prop: "lockNum",
      minWidth: 120
    },
    {
      label: "库存成本均价",
      prop: "avgBuyPrice",
      minWidth: 120,
      formatter: ({ avgBuyPrice }) => dealDataExcept(avgBuyPrice)
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 120,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "商品类目",
      prop: "categoryName",
      minWidth: 150,
      showOverflowTooltip: true,
      formatter: ({ categoryName }) => categoryName || "--"
    },
    {
      label: "关联供应商",
      prop: "supplierName",
      minWidth: 180,
      showOverflowTooltip: true,
      formatter: ({ supplierName }) => supplierName || "--"
    },
    {
      label: "各仓库存",
      fixed: "right",
      prop: "depositoryName",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <el-button link type="primary" onClick={() => showWarehouseStock(row)}>
          查看
        </el-button>
      )
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "商品名称/规格名称",
      prop: "goodsName",
      minWidth: 280,
      align: "left",
      fixed: "left",
      slot: "goodsName"
    },
    {
      label: "商品编码/规格编码",
      prop: "specCode",
      align: "left",
      minWidth: 180,
      formatter: row => row.specCode || row.goodsCode
    },
    {
      label: "所属门店",
      prop: "storeName",
      align: "left",
      width: 130
    },
    {
      label: "商品条码",
      prop: "barCode",
      width: 150,
      slot: "barCode"
    },
    {
      label: "实际库存",
      prop: "actualNum",
      minWidth: 95
    },
    {
      label: "在途库存",
      prop: "sendNum",
      width: 120
    },
    {
      label: "可用库存",
      prop: "canUseNum",
      width: 120
    },
    {
      label: "锁定库存",
      prop: "lockNum",
      minWidth: 120
    },
    {
      label: "库存成本均价",
      prop: "avgBuyPrice",
      minWidth: 120,
      formatter: ({ avgBuyPrice }) => dealDataExcept(avgBuyPrice)
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 120,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "商品类目",
      prop: "categoryName",
      minWidth: 150
    },
    {
      label: "关联供应商",
      prop: "supplierName",
      minWidth: 180
    },
    {
      label: "各仓库存",
      fixed: "right",
      prop: "depositoryName",
      minWidth: 90,
      slot: "depository"
    }
  ];

  function handleUpdate(row) {
    console.log(row);
  }

  /**
   * 显示各仓库存
   * @param row
   */
  const showWarehouseStock = row => {
    addDialog({
      title: "各仓库存",
      props: {
        storeId: row.storeId,
        goodsId: row.goodsId
      },
      width: "1000px",
      sureBtnLoading: true,
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(GodownStock),
      beforeSure: async done => {
        done();
      },
      beforeCancel: done => {
        done();
      }
    });
  };

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量操作 */
  function onBatchStart(goodsStatus) {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const optIds = getKeyList(curSelected, "id");
    console.log("curSelected");
    if (optIds.length <= 0) {
      message("请选择要操作的数据", {
        type: "warning"
      });
    }

    ElMessageBox.confirm(
      `确认要<strong>${goodsStatus == 1 ? "批量启用" : "批量停用"}</strong>选中的商品吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        // await batchUpGoodsStatus({ goodsIds: optIds, goodsStatus });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
        message("操作成功", {
          type: "success"
        });
      })
      .catch(() => {});
  }

  async function onSearch() {
    loading.value = true;

    // 处理请求参数
    let tempForm = { ...form };
    if (tempForm.businessDate && tempForm.businessDate.length > 0) {
      tempForm.businessDateBegin = tempForm.businessDate[0];
      tempForm.businessDateEnd = tempForm.businessDate[1];
    }
    delete tempForm.businessDate;

    const { data } = await getMdStockList(tempForm).catch(
      () => (loading.value = false)
    );
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 200);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.categoryId = "";
    form.businessDate = [];
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect(treeData) {
    let { id, selected } = treeData;
    form.categoryId = selected ? id : "";
    onSearch();
  }

  /** 加载tree */
  const loadTree = async () => {
    treeLoading.value = true;

    // 列表获取
    let params = {
      pageNum: 1,
      pageSize: 999
    };
    let { data } = await getProductPage(params);
    treeData.value = [
      {
        value: 0,
        id: 0,
        label: "全部",
        categoryName: "全部",
        children: handleTree(data.records || [])
      }
    ];
    treeLoading.value = false;
  };

  onMounted(() => {
    if (!treeRef) {
      return;
    }
    loadTree();
    onSearch();

    // 获取仓库列表
    let params = {
      status: 0,
      pageNum: 1,
      pageSize: 500
    };
    getDepositoryPage(params).then(res => {
      selectData.value.ckList = res.data?.records || [];
    });

    // 获取供应商列表
    getSupplierSimplePage(params).then(res => {
      selectData.value.gysList = res.data?.records || [];
    });
  });

  return {
    form,
    loading,
    columns,
    childColumns,
    dataList,
    selectedNum,
    pagination,
    currentTreeData,
    selectData,
    totalForm,
    isStoreManager,
    treeData,
    treeLoading,
    onTreeSelect,
    deviceDetection,
    onSearch,
    resetForm,
    onBatchStart,
    handleUpdate,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel
  };
}
